<script setup lang="ts">
import {reactive, ref,onMounted, onBeforeUnmount} from "vue";
import {EditPen, Lock, Message} from "@element-plus/icons-vue";
import {sendConfirmEmail,resetAccountPassword} from "@/netForAxios/net";
import {ElMessage} from "element-plus";
import 'element-plus/es/components/message/style/css'
import router from "@/router";

const active = ref(0);
const next = ()=>{
  active.value++;
  if(active.value >2){
    active.value=0;
  }
}

const form = reactive({
  password: "",
  password_confirmation: "",
  email: "",
  code: ""
})

const validatePasswordConfirm = (rule, value, callback) => {
  if (value == '') {
    callback(new Error("Password is required"));
  } else if (value != form.password) {
    callback(new Error("Password is not same!"));
  } else {
    callback()
  }
}
const rule = {
  password: [{
    required: true, message: 'please enter your password', trigger: ['blur','change'],
  }, {
    min: 6, max: 20, message: 'Passwords are between six and twenty in length', trigger: ['blur', 'change']
  }],
  password_confirmation: [{
    validator: validatePasswordConfirm,
    trigger: ['blur', 'change']
  }],
  email: [{
    required: true, message: 'please enter your email', trigger: 'blur'
  }, {
    type: 'email', message: 'Please enter truth email address', trigger: ['blur', 'change']
  }],
  code: [{
    required: true,message: 'please enter code', trigger: 'blur'
  }]
}

function getCode() {
  if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)){
    sendConfirmEmail(form.email,()=>{
      next();
    })
  }
}
const formCheck = ref();

function resetPassword(){
  formCheck.value.validate(async (valid) => {
    if (valid) {
      resetAccountPassword(form.email,form.password,form.code,()=>{
        router.push('/')
      });
    }
  })
}
// 存储点击时间戳的数组
const clickTimestamps = ref([])
// 按钮禁用状态
const isButtonDisabled = ref(false)
// 定时器引用
let timerRef = null

// 处理按钮点击事件
const handleClick = () => {
  // 获取当前时间戳
  const currentTime = Date.now()

  // 过滤掉超过一分钟前的时间戳
  clickTimestamps.value = clickTimestamps.value.filter(timestamp => currentTime - timestamp <= 60 * 1000)

  // 检查是否超过限制
  if (clickTimestamps.value.length >= 3) {
    ElMessage.warning('一分钟内最多点击三次，请稍后再试')
    isButtonDisabled.value = true
    //如果有计时器,清除
    if (timerRef) clearTimeout(timerRef)
    //设置计时器
    timerRef = setTimeout(() => {
      isButtonDisabled.value = false
    }, 60 * 1000)
    return
  }
  // 允许点击，将当前时间戳加入数组
  clickTimestamps.value.push(currentTime)
  localStorage.setItem('clickTimestamps', JSON.stringify(clickTimestamps.value))
  getCode();
}

// 页面加载时从 localStorage 恢复状态
onMounted(() => {
  const savedTimestamps = localStorage.getItem('clickTimestamps')
  if (savedTimestamps) {
    clickTimestamps.value = JSON.parse(savedTimestamps)
    const currentTime = Date.now()
    const filteredTimestamps = clickTimestamps.value.filter(timestamp => currentTime - timestamp <= 60 * 1000)

    // 如果仍有记录，设置按钮禁用状态
    if (filteredTimestamps.length >= 3) {
      isButtonDisabled.value = true
      timerRef = setTimeout(() => {
        isButtonDisabled.value = false
      }, 60 * 1000)
    }
  }
})

// 页面卸载时清除定时器
onBeforeUnmount(() => {
  if (timerRef) clearTimeout(timerRef)
})
</script>

<template>
  <div class="ResetBox">
    <div class="Reset-form">
      <div>
        <el-steps :active="active" align-center finish-status="success">
          <el-step title="Step 1" description="验证电子邮件"/>
          <el-step title="Step 2" description="更改密码"/>
        </el-steps>
      </div>
      <div class="step1" v-show="active==0">
        <h1>邮箱验证</h1>
        <p>请在下方输入账号绑定的邮箱</p>
        <el-form :model="form" :rules="rule" ref="formCheck" style="margin-top: 50px" >
          <el-form-item prop="email">
            <el-input v-model="form.email" placeholder="Email">
              <template #prefix>
                <el-icon>
                  <Message/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button @click="handleClick" :disabled="isButtonDisabled"  style="margin-top: 50px; height: 40px;width: 100%;" type="success">下一步</el-button>
      </div>
      <div class="step2" v-show="active==1">
        <h1>重置密码</h1>
        <p>请妥善保存密码,避免丢失</p>
        <el-form :model="form" :rules="rule">
          <el-form-item prop="password">
            <el-input v-model="form.password" maxlength="20" type="password" placeholder="Password">
              <template #prefix>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password_confirmation">
            <el-input v-model="form.password_confirmation" maxlength="20" type="password" placeholder="confirmPassword">
              <template #prefix>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="form.code" maxlength="6" type="text" placeholder="xxxxxx">
              <template #prefix>
                <el-icon>
                  <EditPen/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button @click="resetPassword" style="margin-top: 30px; height: 40px;width: 90%;" type="success">重置密码</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>

.Reset-form {
  width: 60%;
  margin: 50px auto;
  text-align: center;
}
.step1 h1{
  margin-top: 20px;
  letter-spacing: 5px;
  text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
  color: white;
  text-align: center;
}
.step1 p{
  text-align: center;
  color: #b0b0b0;

}
.step2 h1{
  margin-top: 20px;
  letter-spacing: 5px;
  text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
  color: white;
  text-align: center;
}
.step2 p{
  text-align: center;
  color: #b0b0b0;
}
</style>